import { useStorage } from "@vueuse/core";
import { darkTheme } from "naive-ui";
import type { GlobalTheme, GlobalThemeOverrides } from "naive-ui";

export const useThemeNaive = () => {
  // 使用本地存储记住深色模式设置
  const isDark = useStorage("blog-dark-mode", false);
  // 使用本地存储记住选择的主题色
  const themeColor = useStorage("blog-theme-color", "blue");

  // 主题色配置
  const themeColorOptions = {
    blue: {
      primary: "#3b82f6",
      primaryHover: "#2563eb",
      info: "#0ea5e9",
    },
    green: {
      primary: "#10b981",
      primaryHover: "#059669",
      info: "#10b981",
    },
    purple: {
      primary: "#8b5cf6",
      primaryHover: "#7c3aed",
      info: "#8b5cf6",
    },
    pink: {
      primary: "#ec4899",
      primaryHover: "#db2777",
      info: "#ec4899",
    },
  };

  // 获取当前选择的主题色
  const currentThemeColor = computed(
    () => themeColorOptions[themeColor.value as keyof typeof themeColorOptions]
  );

  // 生成 Naive UI 的主题覆盖对象
  const themeOverrides = computed<GlobalThemeOverrides>(() => ({
    common: {
      primaryColor: currentThemeColor.value.primary,
      primaryColorHover: currentThemeColor.value.primaryHover,
      infoColor: currentThemeColor.value.info,
    },
    Button: {
      textColorPrimary: "#fff",
    },
  }));

  // 当前主题对象 (亮色或暗色)
  const theme = computed<GlobalTheme | null>(() =>
    isDark.value ? darkTheme : null
  );

  // 切换深色/浅色模式
  const toggleDarkMode = () => {
    isDark.value = !isDark.value;
    applyThemeToBody();
  };

  // 设置主题色
  const setThemeColor = (color: string) => {
    if (color in themeColorOptions) {
      themeColor.value = color;
      applyThemeToBody();
    }
  };

  // 将主题应用到 body 和 CSS 变量
  const applyThemeToBody = () => {
    const root = document.documentElement;
    const color = currentThemeColor.value;

    // 设置主题色变量
    root.style.setProperty("--primary-color", color.primary);
    root.style.setProperty("--primary-color-hover", color.primaryHover);

    // 设置明暗模式
    if (isDark.value) {
      root.style.setProperty("--bg-primary", "#1a1a1a");
      root.style.setProperty("--bg-secondary", "#2a2a2a");
      root.style.setProperty("--text-primary", "#f5f5f5");
      root.style.setProperty("--text-secondary", "#d4d4d4");
      root.classList.add("dark");
    } else {
      root.style.setProperty("--bg-primary", "#f5f5f5");
      root.style.setProperty("--bg-secondary", "#ffffff");
      root.style.setProperty("--text-primary", "#1a1a1a");
      root.style.setProperty("--text-secondary", "#4a4a4a");
      root.classList.remove("dark");
    }
  };

  onMounted(() => {
    applyThemeToBody();
  });

  return {
    isDark,
    theme,
    themeOverrides,
    themeColor,
    toggleDarkMode,
    setThemeColor,
    themeColors: Object.keys(themeColorOptions),
  };
};
